<template>
    <div>
        <el-card>
            <div slot="header">
                <span>
                    <span>基原名称：</span>
                    <el-input v-model='searchKeyword' placeholder='请输入' style='width:300px;margin-right:10px;'></el-input>
                </span>
                <span>
                    <span>批号：</span>
                    <el-input v-model='searchBatch' placeholder='请输入' style='width:300px;margin-right:10px;'></el-input>
                </span>
                <el-button class='theme-button' @click='search()'>搜索</el-button>
                <el-button  @click='reset()'>重置</el-button>
            </div>
            <el-row>
                <el-col :span='24'>
                    <el-button round class='theme-button' icon='el-icon-plus' style='float: right;background-color: #02B386;color: #fff' @click='handleAdd'>新增</el-button>
<!--        2024.5.27 产品说不要了            -->
<!--                    <el-upload-->
<!--                        class="upload-import"-->
<!--                        ref="upload"-->
<!--                        action=""-->
<!--                        :on-change="importExcel"-->
<!--                        accept=".xlsx,.xls"-->
<!--                        :show-file-list='false'-->
<!--                        :auto-upload="false">-->
<!--                        <el-button class='theme-button' slot="trigger" size="small">导入模板</el-button>-->
<!--                    </el-upload>-->
<!--                    <el-button class='theme-button' style='float: right;margin-right: 10px' @click='downloadTemplate'>下载导入模板</el-button>-->
                </el-col>
            </el-row>
            <el-row style='margin: 20px 0'>
                <el-col :span='24'>
                    <el-table border :data='tableData' :default-sort = "{prop: 'jyName', order: 'descending'}" :header-cell-style="{ background:'rgba(2,179,134,0.1)'}">
                        <el-table-column sortable prop='jyName' label='基原名称'></el-table-column>
                        <el-table-column sortable prop='batch' label='批号'></el-table-column>
<!--                        <el-table-column prop='reproductive' label='繁殖材料'></el-table-column>-->
                        <el-table-column prop='grade' label='等级'></el-table-column>
                        <el-table-column prop='source' label='来源'></el-table-column>
                        <el-table-column label='操作'>
                            <template slot-scope="scope">
                                <el-button type="text" style='color: #F7BE17;margin-right: 10px' @click="handleView( scope.row)">详情</el-button>
                                <el-button type="text" style='color: #409EFF;margin-right: 10px' @click="handleEdit(scope.row)">编辑</el-button>
                                <el-button type="text" style='color: #FF3446;' @click="handleDelete(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[10, 20, 30, 40]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </el-col>
            </el-row>
        </el-card>

        <el-dialog :visible.sync="viewShow" width="60%">
            <el-descriptions title="种源信息" size='medium'>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="基原">{{currentView.jyName}}</el-descriptions-item>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="批号">{{currentView.batch}}</el-descriptions-item>
<!--                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="繁殖材料">{{currentView.reproductive}}</el-descriptions-item>-->
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="发芽率">{{currentView.germination}}%</el-descriptions-item>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="成活率">{{currentView.survival}}%</el-descriptions-item>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="等级">{{currentView.grade}}</el-descriptions-item>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="培育地点">{{currentView.cultivation}}</el-descriptions-item>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="贮藏条件">{{currentView.storage}}</el-descriptions-item>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="来源">{{currentView.source}}</el-descriptions-item>
            </el-descriptions>
            <span class='line'></span>
            <el-descriptions title="" direction='vertical' size='medium'>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="品种介绍">{{currentView.introduce}}</el-descriptions-item>
                <el-descriptions-item label-class-name="my-label" content-class-name="my-content" label="检验报告">
                    <img style='width: 300px' :src='currentView.checkImg'/>
                </el-descriptions-item>
            </el-descriptions>
        </el-dialog>
        <el-dialog :title='modalTitle' :visible.sync='modalShow' width='80%'>
            <el-row :gutter='20'>
                <el-form :model='formData' label-width='100px' :rules='rules' ref='formData'>
                    <el-col :span='8'>
                        <el-form-item label='基原名称:' required prop='jyName'>
                            <el-select class='form-item' placeholder='请选择' @change='jyChange' v-model='formData.jyName'>
                                <el-option v-for='item in rootList' :key='item.id' :label='item.name' :value='item.name'></el-option>
                            </el-select>
                        </el-form-item>
<!--                        <el-form-item label='繁殖材料:' required prop='reproductive'>-->
<!--                            <el-select class='form-item' placeholder='请选择' v-model='formData.reproductive'>-->
<!--                                <el-option label='种子' value='种子'></el-option>-->
<!--                                <el-option label='种苗' value='种苗'></el-option>-->
<!--                                <el-option label='其他' value='其他'></el-option>-->
<!--                                <el-option label='种根' value='种根'></el-option>-->
<!--                            </el-select>-->
<!--                        </el-form-item>-->
                        <el-form-item label='等级:' required prop='grade'>
                            <el-select class='form-item' placeholder='请选择' v-model='formData.grade'>
                                <el-option label='一级' value='一级'></el-option>
                                <el-option label='二级' value='二级'></el-option>
                                <el-option label='三级' value='三级'></el-option>
                                <el-option label='特级' value='特级'></el-option>
                                <el-option label='其他' value='其他'></el-option>
                            </el-select>
                        </el-form-item>
<!--                        <el-form-item label='种源成本:'>-->
<!--                            <el-input class='form-item' v-model='formData.cost'>-->
<!--                                <template slot='suffix'>元</template>-->
<!--                            </el-input>-->
<!--                        </el-form-item>-->
                    </el-col>
                    <el-col :span='8'>
                        <el-form-item label='来源:' required prop='source'>
                            <el-select class='form-item' placeholder='请选择' v-model='formData.source'>
                                <el-option label='自培育（不可溯源）' value='自培育（不可溯源）'></el-option>
                                <el-option label='外购(不可溯源)' value='外购(不可溯源)'></el-option>
                                <el-option label='自培育（可溯源）' value='自培育（可溯源）'></el-option>
                                <el-option label='外购(可溯源)' value='外购(可溯源)'></el-option>
                            </el-select>
                        </el-form-item>
<!--                        <el-form-item label='发芽率:'>-->
<!--                            <el-input class='form-item' v-model='formData.germination'>-->
<!--                                <template slot='suffix'>%</template>-->
<!--                            </el-input>-->
<!--                        </el-form-item>-->
                        <el-form-item label='培育地点:'>
                            <el-input class='form-item' placeholder='输入地点' v-model='formData.cultivation'></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span='8'>
                        <el-form-item label='批号:' required prop='batch'>
                            <el-input class='form-item' placeholder='输入批号'  v-model='formData.batch'></el-input>
                        </el-form-item>
<!--                        <el-form-item label='成活率:'>-->
<!--                            <el-input class='form-item' v-model='formData.survival'>-->
<!--                                <template slot='suffix'>%</template>-->
<!--                            </el-input>-->
<!--                        </el-form-item>-->
                        <el-form-item label='贮藏条件:'>
                            <el-input class='form-item' placeholder='贮藏条件' v-model='formData.storage'></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span='24'>
                        <el-form-item label='品种介绍:'>
                            <el-input  type='textarea' placeholder='品种介绍' :rows='3' v-model='formData.introduce'></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span='12'>
                        <el-form-item label='检验报告:'>
                           <myUpload :files='formData.checkImgArr' :maxNum='1' :file-list='fileListReport' @getUpload='getImgUrl'></myUpload>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
            <div slot='footer'>
                <el-button @click='modalShow=false'>取消</el-button>
                <el-button class='theme-button' @click='confirm'>确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import myUpload from '@/components/common/myUpload.vue';
import { savePlantSeed, getPlantSeed, getPlantSeedList, deletePlantSeed } from '@/request/api';
export default {
    name: 'provenance',
    components: { myUpload },
    data() {
        return {
            searchKeyword: '',
            searchBatch:'',

            rootList:[],
            tableData: [],
            currentPage: 1,
            pageSize: 10,
            total: 0,

            viewShow:false,
            currentView:{
                jyName:'',
                batch:'',
                reproductive:'',
                grade:'',
                source:'',
                germination:'',
                survival:'',
                storage:'',
                introduce:'',
                cultivation:'',
            },

            modalShow:false,
            modalTitle:'新增',
            currentModal:{
                jyName:'',
                batch:'',
                reproductive:'',
                grade:'',
                source:'',
                germination:'',
                survival:'',
                storage:'',
                introduce:'',
            },
            fileListReport:[],

            rules:{
                jyName: [
                    { required: true, message: '请选择基原名称', trigger: 'blur' },
                ],
                reproductive: [
                    { required: true, message: '请选择繁殖材料', trigger: 'blur' },
                ],
                grade: [
                    { required: true, message: '请选择种源等级', trigger: 'blur' },
                ],
                source: [
                    { required: true, message: '请选择来源', trigger: 'blur' },
                ],
                batch: [
                    { required: true, message: '请输入批号', trigger: 'blur' },
                ],
            },
            formData:{
                jyName:'',//基原名称
                batch:'',//批号
                latinName:'',//基原拉丁文名
                reproductive:'',//繁殖材料
                grade:'',//种源等级
                source:'',//来源
                germination:'',//发芽率
                survival:'',//成活率
                storage:'',//贮藏条件
                introduce:'',//种源介绍
                cost:'',//成活率
                cultivation:'',
                checkImgArr:[],
            },
        }
    },
    mounted() {
        this.getRootInfo()
        this.getTableData()
    },
    watch:{
        modalShow(val){
            if(!val){
                this.fileListReport = []
            }
        }
    },
    methods:{
        //随机批次，ZY+当前日期+随机3位数
        getBatch(){
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth()+1;
            let day = date.getDate();
            let hour = date.getHours();
            let minute = date.getMinutes();
            let second = date.getSeconds();
            let random = Math.floor(Math.random()*1000);
            let batch = 'ZY'+year+month+day+hour+minute+second+random;
            this.formData.batch = batch;
       },
        async getTableData(){
            let params = {
                jyName:this.searchKeyword,
                batch:this.searchBatch,
                page:this.currentPage,
                pageSize:this.pageSize,
            }
            const res = await getPlantSeedList(params)
            if(res.code == 200){
                this.tableData = res.data.content;
                this.total = res.data.totalElements;
            }
        },
        async getRootInfo(){
            const res = await getPlantSeed();
            if(res.code == 200){
                this.rootList = res.data
            }
        },
        getImgUrl({res,file,fileList}){
            this.formData.checkImgArr = [
                {
                    url:localStorage.getItem('requestUrl')+'file/show/'+res.data.fileName,
                    name:res.data.fileName,
                    status:'success'
                }
            ]
        },
        search(){
            this.searchKeyword = this.searchKeyword.trim();
            this.getTableData()
        },
        reset(){
            this.searchBatch = '';
            this.searchKeyword = ''
            this.getTableData()
        },
        importExcel(file){
            let formData = new FormData();
            formData.append('file', file.raw);
            let config = {
                headers:{'Content-Type':'multipart/form-data'}
            };
            // 导入模板的接口(formData).then((res) =>{
            //     if (res.code == 200) {
            //         this.$notify({
            //             title: '操作成功',
            //             message: '导入成功',
            //             type: 'success'
            //         });
            //         this.init()
            //     } else{
            //         this.$notify.error({
            //             title: '操作失败',
            //             message: '导入失败',
            //             type: 'error'
            //         });
            //     }
            // })
        },
        downloadTemplate(){
            const companyId =  localStorage.getItem('companyId')
            let templateUrl ="/plant/template/模板下载地址&companyId="
            window.location.href = "http://47.108.220.160:90/jcApi/plant" + templateUrl + companyId
        },
        async request(){
            const res = await savePlantSeed(this.formData)
            if(res.code == 200){
                console.log(res);
                this.$notify({
                    title: '操作成功',
                    message: '新增成功',
                    type: 'success'
                });
                this.modalShow = false
                this.currentPage = 1
                this.getTableData()
                this.formData = {
                    jyName:'',//基原名称
                    batch:'',//批号
                    latinName:'',//基原拉丁文名
                    reproductive:'',//繁殖材料
                    grade:'',//种源等级
                    source:'',//来源
                    germination:'',//发芽率
                    survival:'',//成活率
                    storage:'',//贮藏条件
                    introduce:'',//种源介绍
                    cost:'',//成活率
                }
            }else{
                this.$notify.error({
                    title: '操作失败',
                    message: res.msg,
                    type: 'error'
                });
                this.modalShow = false
                this.currentPage = 1
                this.getTableData()
                this.formData = {
                    jyName:'',//基原名称
                    batch:'',//批号
                    latinName:'',//基原拉丁文名
                    reproductive:'',//繁殖材料
                    grade:'',//种源等级
                    source:'',//来源
                    germination:'',//发芽率
                    survival:'',//成活率
                    storage:'',//贮藏条件
                    introduce:'',//种源介绍
                    cost:'',//成活率
                }
            }
        },
        jyChange(name){
            console.log(name);
            const find = this.rootList.find(item => item.name === name)
            if(find){
                //由于sl后端需要latinName这个字段所以这样赋值
                this.formData.latinName = find.latinName
                this.formData.jyId = find.id
                this.formData.jyName = find.name
            }
        },
        confirm(){
            if(this.modalTitle == '新增'){
                this.$refs.formData.validate(async (valid) => {
                    if (valid){
                        console.log('新增：',this.formData);
                        this.request()
                    }
                })
            }else if(this.modalTitle == '编辑'){
                this.$refs.formData.validate((valid) => {
                    if (valid){
                        console.log('编辑：',this.formData);
                        this.request()
                    }
                })
            }

        },
        handleAdd(){
            this.modalTitle = '新增'
            this.modalShow = true
            this.formData = {
                jyName:'',//基原名称
                batch:'',//批号
                latinName:'',//基原拉丁文名
                reproductive:'',//繁殖材料
                grade:'',//种源等级
                source:'',//来源
                germination:'',//发芽率
                survival:'',//成活率
                storage:'',//贮藏条件
                introduce:'',//种源介绍
                cost:'',//成活率
            }
            this.$nextTick(()=>{
                this.$refs.formData.resetFields()
                this.getBatch()

            })
        },
        handleView(row){
            this.viewShow = true
            let data = JSON.stringify(row)
            data = JSON.parse(data)
            this.currentView = data
            if(this.currentView.checkImg === "null"){
                this.currentView.checkImg = []
            }
            this.currentView.checkImg = this.currentView.checkImg.length ? JSON.parse(this.currentView.checkImg)[0].url:this.currentView.checkImg
        },
        handleEdit(row){
            this.modalTitle = '编辑'
            this.modalShow = true
            this.formData = row
            if(this.formData.checkImg === "null"){
                this.formData.checkImg = []
            }
            if(typeof this.formData.checkImg == 'string'){
                this.formData.checkImgArr = JSON.parse(this.formData.checkImg)
                this.fileListReport = this.formData.checkImgArr
            }
        },
        async handleDelete(row){
            const res = await deletePlantSeed('?id='+row.id)
            if (res.code == 200){
                this.$notify({
                    title: '操作成功',
                    message: res.msg,
                    type: 'success'
                });
                this.getTableData()
            }else{
                this.$notify({
                    title: '操作失败',
                    message: res.msg,
                    type: 'success'
                });
                this.getTableData()
            }
        },
        handleSizeChange(size){
            this.pageSize = size
            this.getTableData()
        },
        handleCurrentChange(curPage){
            this.currentPage = curPage
            this.getTableData()
        },
    }
};
</script>
<style>
.my-label{
    padding: 10px;
    font-size: 16px;
}
.my-content{
    padding: 10px;
    font-size: 16px;

}
</style>
<style lang='less' scoped>
@import url('@/assets/css/common');
.el-pagination{
    padding: 10px;
    text-align: right;
}
.line{
    width: 100%;
    height: 1px;
    background-color: #e6e6e6;
    margin-top: 10px;
    margin-bottom: 10px;
    display: inline-block;
}
.form-item{
    width: 100%;
}
</style>
